package com.watson.retryer.service;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author watson
 * @Date 2022/7/14 12:23
 * @Version 1.0
 */
@Slf4j
public class GuavaService {


    public static void main(String[] args) throws Exception {
        Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
                // 设置自定义段元重试源
                .retryIfResult(Predicates.<Integer>isNull())
                // 设置异常重试源
                .retryIfExceptionOfType(Exception.class)
                // 设置异常重试源
                .retryIfRuntimeException()
                // 设置重试次数    设置重试超时时间？？？？
                .withStopStrategy(StopStrategies.stopAfterAttempt(5))
                // 设置每次重试间隔
                .withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS))
                .build();

        Callable<Integer> task = new Callable<Integer>() {
            int i = 0;

            @Override
            public Integer call() throws Exception {
                i++;
                log.info("第{}次执行调用三方接口！", i);
                if (i < 3) {
                    log.info("模拟执行失败");
                    throw new IOException("异常");
                }
                return i;
            }
        };

        try {
            retryer.call(task);
        } catch (ExecutionException e) {
            log.error("error", e);
        } catch (RetryException e) {
            log.error("error", e);
        }

        Integer result = task.call();
        log.info("成功输出结果：{}", result);
    }

}


